// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
const { getInviteUser } = require('./common/common')
const { setProfitSharing } = require('./common/setProfitSharing')
const { setNewLevel } = require("./common/setNewLevel.js")
const { setNewProfit } = require("./common/setNewProfit.js")
const { setNewBookProfit } = require("./common/setNewBookProfit.js")
const db = uniCloud.database();
const dbCmd = db.command

module.exports = {
	_before: function () { // 通用预处理器

	},
	test:async function({id,orderid}){
		// return await setNewLevel({id,orderid})
		// return await setNewProfit({id,price:10000,orderid})
	},
	/**
	 * 设置相应等级分润--学习法
	 * @param {String} id   用户当前用户ID
	 * @param {Number} type   分润类型 0 会员购买 1活动购买
	 * @param {Number} price   支付金额
	 * @returns
	 */
	setNewBookProfit,
	// setProfitSharing:async function({id,price,orderid=''}){
	// 	// return await setNewProfit({id,price,orderid})
	// 	return await setProfitSharing({id,price,orderid})
	// },
	
	// /**
	//  * 更新归属关系信息
	//  * @param {String} id   当前用户ID
	//  * @returns
	//  */
	setIdentity:async function({id,orderid}){
		return await setNewLevel({id,orderid})
		// return await getInviteUser({id,orderid})
	},
	/**
	 * 设置相应等级分润
	 * @param {String} id   用户当前用户ID
	 * @param {Number} type   分润类型 0 会员购买 1活动购买
	 * @param {Number} price   支付金额
	 * @returns
	 */
	setProfitSharing:async function({id,price,orderid=''}){
		return await setNewProfit({id,price,orderid})
		// return await setProfitSharing({id,price,orderid})
	},
	
	/**
	 * 设置礼物分润
	 * @param {String} id   用户当前用户ID
	 * * @param {String} pid   收益人
	 * @param {Number} orderid   订单编号
	 * @param {Number} price   支付金额
	 * @returns
	 */
	setProfitGift:async function(data){
		data.create_time = new Date().getTime()
		console.log("=====>>>>",data);
		try{
			// 添加记录
			let addLog = await db.collection('wolf-gift-log').add(data)
			//更新受益人的余额
			let upUser = await db.collection("uni-id-users").doc(data.pid).update({
				gift_money:dbCmd.inc(data.price*0.5)
			})
			let upMyUser = await db.collection("uni-id-users").doc(data.uid).update({
				gift_money:dbCmd.inc(-data.price)
			})
			//设置分润
			let setProfit = await setProfitSharing({
				id:data.pid,
				price:data.price,
				orderid:data.order_no
			})
			console.log("=========>>>>>",addLog,upUser,upMyUser,setProfit);
			return {
				errCode:0,
				errMsg:"赠送成功",
				id:addLog.id
			}
		}catch(e){
			console.log("setProfitGift======>>>>>>>",e);
			return {
				errCode:1,
				errMsg:"赠送失败" + JSON.stringify(e)
			}
		}
		// return await setProfitSharing({id,price,orderid})
	}
}
